package com.guchenbo.schedule;

import com.guchenbo.schedule.biz.UserMgr;
import net.sf.cglib.proxy.*;

import java.lang.reflect.Method;

/**
 * @author guchenbo
 * @date 2021/4/12
 */
public class CglibDemo {

  public static void main(String[] args) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(UserMgr.class);

    Callback callback = new MethodInterceptor() {
      public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
          throws Throwable {
        System.out.println("in proxy");
        return proxy.invokeSuper(obj, args);
      }
    };

    Callback callback2 = new MethodInterceptor() {
      public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
          throws Throwable {
        System.out.println("in proxy2");
        return proxy.invokeSuper(obj, args);
      }
    };

    CallbackFilter callbackFilter = new CallbackFilter() {
      public int accept(Method method) {
        if (method.getParameterCount() > 0) {
          return 1;
        }
        return 0;
      }
    };
    Callback[] callbacks = {callback, callback2};

//    enhancer.setCallback(callback);
    enhancer.setCallbacks(callbacks);
    enhancer.setCallbackFilter(callbackFilter);
    Object obj = enhancer.create();
    UserMgr userMgr = (UserMgr) obj;
    String str = userMgr.hello();
    System.out.println(str);
    System.out.println(userMgr.hello("jay"));
  }

}
